﻿using Newtonsoft.Json;
using System.Xml;

namespace Api.Utils
{
    public static class DynamicConvert
    {
        public static string ToXmlString(dynamic value, string rootElementName)
        {
            string jsonString = ToJsonString(value);
            string xmlString = JsonConvert.DeserializeXmlNode(
                jsonString, rootElementName).OuterXml;
            return xmlString;
        }

        public static string ToJsonString(dynamic value)
        {
            string jsonString = JsonConvert.SerializeObject(value);
            return jsonString;
        }

        public static dynamic FromXmlString(string xmlString)
        {
            var xmlDocu = new XmlDocument();
            xmlDocu.LoadXml(xmlString);
            string jsonString = JsonConvert.SerializeXmlNode(
                xmlDocu, Newtonsoft.Json.Formatting.None, true);
            return FromJsonString(jsonString);
        }

        public static dynamic FromJsonString(string jsonString)
        {
            dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
            return dynamicObject;
        }
    }
}